package y24.m5;

import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.Scanner;

public class Compute {
    private JFrame frame;
    private JPanel panel;
    private JLabel jLabel = new JLabel("=");
    private JTextField num1, num2, result;
    private JButton addButton, subtractButton, multiplyButton, divideButton;
    private double n1,n2;

    public Compute() {
        frame = new JFrame("计算器");
        panel = new JPanel(new GridLayout(2,4));
        num1 = new JTextField(10);
        num2 = new JTextField(10);
        result = new JTextField(10);
        result.setEditable(false);

        addButton = new JButton("+");
        subtractButton = new JButton("-");
        multiplyButton = new JButton("*");
        divideButton = new JButton("/");

        // 添加事件监听器
        addButton.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                getNum();
                double r = n1 + n2;
                result.setText(String.valueOf(r));
            }
        });

        subtractButton.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                getNum();
                double r = n1 - n2;
                result.setText(String.valueOf(r));
            }
        });

        multiplyButton.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                getNum();
                double r = n1 * n2;
                result.setText(String.valueOf(r));
            }
        });

        divideButton.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                getNum();
                if (n2 != 0) {
                    double r = n1 / n2;
                    result.setText(String.valueOf(r));
                } else {
                    result.setText("除数不能为0");
                }
            }
        });

        panel.add(num1);
        panel.add(num2);
        panel.add(jLabel);
        panel.add(result);
        panel.add(addButton);
        panel.add(subtractButton);
        panel.add(multiplyButton);
        panel.add(divideButton);

        frame.setLocationRelativeTo(null);
        frame.add(panel);
        frame.setSize(300, 150);
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.setVisible(true);
    }

    private void getNum() {
        n1 = Double.parseDouble(num1.getText());
        n2 = Double.parseDouble(num2.getText());
    }

    public static void main(String[] args) {
        new Compute();
    }
}
